package com.shiwaixiangcun.authz.shiro.filter;

import com.alibaba.fastjson.JSON;
import com.shiwaixiangcun.core.web.response.MonkeyResponseDto;
import com.shiwaixiangcun.core.web.response.ResponseCode;
import com.shiwaixiangcun.utils.MonkeyUtils;
import com.shiwaixiangcun.utils.SignUtils;
import com.shiwaixiangcun.utils.WebUtils;
import org.apache.shiro.web.servlet.OncePerRequestFilter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.Map;

/**
 * Created by Administrator on 2017/5/10.
 */
public class AppSignFilter /*extends OncePerRequestFilter */{
    private Logger logger = LoggerFactory.getLogger(AppSignFilter.class);

//    @Override
    protected void doFilterInternal(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        Map<String, String> params = MonkeyUtils.getParameterMap(request);
        logger.info("============ request params ===============");
        logger.info("{}", JSON.toJSONString(params));

        String sign = params.get("sign");
        if (SignUtils.verification(params, sign)) {
            chain.doFilter(request, response);
            return;
        }

        logger.info("The Request Sign Fail,The sign:{}", sign);
        MonkeyResponseDto responseDto = new MonkeyResponseDto();
        responseDto.fail(ResponseCode.REQUEST_SIGN_FAIL, "请求签名失败");
        WebUtils.writeJSON(response, responseDto);
    }


    public static void main(String[] args) {
        System.out.println(MonkeyUtils.uuid());
    }
}
